package com.bqdu.service;

import com.bqdu.common.Constant;
import com.bqdu.demo1.domain.SeckillCommodity;
import com.bqdu.demo1.domain.SeckillOrder;
import com.bqdu.demo1.service.SeckillCommodityService;
import com.bqdu.demo1.service.SeckillOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private SeckillOrderService seckillOrderService;
    @Autowired
    private SeckillCommodityService seckillCommodityService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Transactional
    public boolean generateOrder(SeckillCommodity seckillCommodity) throws Exception {
        Long commodityId = seckillCommodity.getId();
        //先减少商品的库存
        boolean b = seckillCommodityService.reduceStock(commodityId);
        //同时也要减少redis存储的商品库存
//        Long decrement = redisTemplate.opsForValue().decrement(Constant.COMMODITY_ID_PREFIX + commodityId);
//        log.info("库存量"+decrement);
        //创建一个订单
//        if(1==1){
//            throw new RuntimeException("主动错误");
//        }
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setCommodity_id(commodityId);
        seckillOrder.setNum(1);
        seckillOrder.setPrice(seckillCommodity.getPrice());
        boolean save = seckillOrderService.save(seckillOrder);
        return b&&save;
    }
}
